package com.petvc.tv

import android.content.Context
import android.content.SharedPreferences
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.util.concurrent.TimeUnit

class AuthService {
    companion object {
        private const val PREFS_NAME = "PetTV_Auth"
        private const val KEY_ACCESS_TOKEN = "access_token"
        private const val KEY_REFRESH_TOKEN = "refresh_token"
        private const val KEY_USER_ID = "user_id"
        private const val KEY_USERNAME = "username"
        private const val KEY_IS_LOGGED_IN = "is_logged_in"
        
        /**
         * 用户登录
         */
        suspend fun login(
            context: Context,
            username: String,
            password: String
        ): LoginResult = withContext(Dispatchers.IO) {
            val startTime = System.nanoTime()
            LogUtils.logAuth("开始登录流程: 用户=$username")
            
            try {
                // 检查网络连接
                if (!NetworkUtils.isNetworkAvailable(context)) {
                    LogUtils.logAuth("网络连接不可用")
                    return@withContext LoginResult(
                        success = false,
                        message = "网络连接不可用，请检查网络设置",
                        userData = null
                    )
                }
                
                LogUtils.logAuth("网络连接正常")
                
                // 验证输入参数
                if (username.isBlank() || password.isBlank()) {
                    LogUtils.logAuth("输入参数验证失败: 用户名或密码为空")
                    return@withContext LoginResult(
                        success = false,
                        message = "请输入用户名和密码",
                        userData = null
                    )
                }
                
                LogUtils.logAuth("输入参数验证通过")
                
                // 构建登录请求数据
                val loginData = JSONObject().apply {
                    put("username", username)
                    put("password", password)
                }
                
                LogUtils.logAuth("构建登录请求数据: ${loginData}")
                LogUtils.logAuth("发送登录请求到: ${ApiConfig.Auth.LOGIN}")
                
                // 发送登录请求
                val response = NetworkUtils.postRequest(
                    url = ApiConfig.Auth.LOGIN,
                    jsonData = loginData.toString()
                )
                
                LogUtils.logAuth("收到登录响应: success=${response.success}, message=${response.message}")
                
                if (response.success) {
                    // 解析响应数据
                    LogUtils.logAuth("开始解析用户数据")
                    val userData = parseUserData(response.data)
                    LogUtils.logUserData(userData)
                    
                    if (userData != null) {
                        // 保存登录状态和令牌
                        LogUtils.logAuth("保存登录数据到本地存储")
                        saveLoginData(context, userData)
                        LogUtils.logToken(userData.accessToken)
                        
                        val duration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)
                        LogUtils.logPerformance("登录流程", duration)
                        LogUtils.logLogin(username, true, "登录成功")
                        
                        return@withContext LoginResult(
                            success = true,
                            message = "登录成功",
                            userData = userData
                        )
                    } else {
                        LogUtils.logAuth("用户数据解析失败")
                        LogUtils.logLogin(username, false, "登录响应数据解析失败")
                        
                        return@withContext LoginResult(
                            success = false,
                            message = "登录响应数据解析失败",
                            userData = null
                        )
                    }
                } else {
                    LogUtils.logAuth("登录请求失败: ${response.message}")
                    LogUtils.logLogin(username, false, response.message)
                    
                    return@withContext LoginResult(
                        success = false,
                        message = response.message,
                        userData = null
                    )
                }
            } catch (e: Exception) {
                LogUtils.logAuth("登录过程发生异常: ${e.message}")
                LogUtils.logLogin(username, false, "登录失败: ${e.message}")
                
                return@withContext LoginResult(
                    success = false,
                    message = "登录失败: ${e.message}",
                    userData = null
                )
            }
        }
        
        /**
         * 解析用户数据
         */
        private fun parseUserData(data: Any?): UserData? {
            return try {
                LogUtils.logAuth("开始解析用户数据: data类型=${data?.javaClass?.simpleName}")
                
                if (data is JSONObject) {
                    LogUtils.logAuth("数据是JSONObject类型")
                    val user = data.optJSONObject("user")
                    val tokens = data.optJSONObject("tokens")
                    
                    LogUtils.logAuth("解析结果: user=${user != null}, tokens=${tokens != null}")
                    
                    if (user != null && tokens != null) {
                        val userData = UserData(
                            id = user.optString("id"),
                            username = user.optString("username"),
                            accessToken = tokens.optString("access_token"),
                            refreshToken = tokens.optString("refresh_token")
                        )
                        LogUtils.logAuth("用户数据解析成功: ID=${userData.id}, 用户名=${userData.username}")
                        userData
                    } else {
                        LogUtils.logAuth("用户数据解析失败: user或tokens为空")
                        null
                    }
                } else {
                    LogUtils.logAuth("数据不是JSONObject类型: ${data?.javaClass?.simpleName}")
                    null
                }
            } catch (e: Exception) {
                LogUtils.logAuth("解析用户数据时发生异常: ${e.message}")
                null
            }
        }
        
        /**
         * 保存登录数据到本地存储
         */
        private fun saveLoginData(context: Context, userData: UserData) {
            LogUtils.logAuth("开始保存登录数据到本地存储")
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            prefs.edit().apply {
                putString(KEY_ACCESS_TOKEN, userData.accessToken)
                putString(KEY_REFRESH_TOKEN, userData.refreshToken)
                putString(KEY_USER_ID, userData.id)
                putString(KEY_USERNAME, userData.username)
                putBoolean(KEY_IS_LOGGED_IN, true)
                apply()
            }
            LogUtils.logAuth("登录数据保存完成")
        }
        
        /**
         * 检查是否已登录
         */
        fun isLoggedIn(context: Context): Boolean {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            return prefs.getBoolean(KEY_IS_LOGGED_IN, false) &&
                   prefs.getString(KEY_ACCESS_TOKEN, null) != null
        }
        
        /**
         * 获取当前用户信息
         */
        fun getCurrentUser(context: Context): UserData? {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            val isLoggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false)
            
            if (!isLoggedIn) return null
            
            val accessToken = prefs.getString(KEY_ACCESS_TOKEN, null)
            val refreshToken = prefs.getString(KEY_REFRESH_TOKEN, null)
            val userId = prefs.getString(KEY_USER_ID, null)
            val username = prefs.getString(KEY_USERNAME, null)
            
            if (accessToken != null && userId != null && username != null) {
                return UserData(
                    id = userId,
                    username = username,
                    accessToken = accessToken,
                    refreshToken = refreshToken ?: ""
                )
            }
            
            return null
        }
        
        /**
         * 获取访问令牌
         */
        fun getAccessToken(context: Context): String? {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            return prefs.getString(KEY_ACCESS_TOKEN, null)
        }
        
        /**
         * 用户登出
         */
        fun logout(context: Context) {
            // 停止心跳发送
            HeartbeatManager.stopHeartbeat()
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            prefs.edit().clear().apply()
        }
        
        /**
         * 清除登录数据
         */
        fun clearLoginData(context: Context) {
            val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            prefs.edit().clear().apply()
        }
    }
}

/**
 * 登录结果数据类
 */
data class LoginResult(
    val success: Boolean,
    val message: String,
    val userData: UserData?
)

/**
 * 用户数据类
 */
data class UserData(
    val id: String,
    val username: String,
    val accessToken: String,
    val refreshToken: String
) 